#!/bin/sh

# ubus -v list luci.antiblock
# ubus -S call luci.antiblock read_domains
# ubus -S call luci.antiblock write_domains '{"domains":["test0.com","test1.com","test2.com"]}'

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

get_file_path() {
    file_path="$(uci -q get antiblock.config.file)"
}

read_domains() {
    get_file_path

    json_init
    if [ -n "$file_path" ]; then
        if [ ! -f "$file_path" ]; then
            touch "$file_path"
        fi

        json_add_array "domains"
        file_data=$(cat $file_path)
        for domain in $file_data; do
            json_add_string "" "$domain"
        done
        json_close_array
    else
        json_add_array "empty"
        json_close_array
    fi
    json_dump
    json_cleanup
}

write_domains() {
    get_file_path

    if [ -n "$file_path" ]; then
        if [ ! -f "$file_path" ]; then
            touch "$file_path"
        fi

        json_load "$1"
        json_get_values values "domains"
        >$file_path
        for key in $values; do
            echo "$key" >>$file_path
        done
        json_cleanup

        /etc/init.d/antiblock restart
    fi
}

case "$1" in
list)
    json_init
    json_add_object "read_domains"
    json_close_object
    json_add_object "write_domains"
    json_add_string 'domains' "domains"
    json_close_object
    json_dump
    json_cleanup
    ;;
call)
    case "$2" in
    read_domains)
        read_domains
        ;;
    write_domains)
        read -r input
        write_domains "$input"
        ;;
    *)
        return 0
        ;;
    esac
    ;;
*)
    return 0
    ;;
esac
